package core {

	import common.loader.LoaderManager;
	import common.loader.LoaderType;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	
	import globals.Global;
	import globals.Setting;
	
	import ui.units.UnitView;
	
	import util.Logger;

	public class AssetsManager {
		
		private static const assets:Dictionary = new Dictionary();

		public function AssetsManager() {
		}
		
		public function getAssets(aid:String, type:uint = LoaderType.BINARY, handler:Function = null):Object {
			if (assets[aid] != null) {
				return assets[aid];
			} else {
				LoaderManager.add(aid, type, handler);
				return null;
			}
		}
		
		public function getIconBitmapData(key:String):BitmapData {
			return getAssetsAsBitmapData("I" + key, "icon");
		}
		
		public function getAssetsAsBitmapData(key:String, domainKey:String = ""):BitmapData {
			if (domainKey == "") {
				domainKey = "ui";
			}
			var domain:ApplicationDomain = Setting.ASSETS["resources/" + domainKey + ".swf"];
			if (domain == null) {
				Logger.error("can not found ui domain " + domainKey);
			}
			if (!domain.hasDefinition(key)) {
				Logger.error("asset " + key + " not found in " + domainKey);
				return null;
			}
			var clazz:Class = domain.getDefinition(key) as Class;
			return new clazz(0, 0) as BitmapData;
		}
		
		public function getAssetsAsMovieClip(key:String, domainKey:String = ""):MovieClip {
			if (domainKey == "") {
				domainKey = "ui";
			}
			var domain:ApplicationDomain = Setting.ASSETS["resources/" + domainKey + ".swf"];
			if (!domain.hasDefinition(key)) {
				Logger.error("asset " + key + " not found in " + domainKey);
				return null;
			}
			var clazz:Class = domain.getDefinition(key) as Class;
			return new clazz() as MovieClip;
		}
		
		private function getEmbed(domain:ApplicationDomain, key:String):* {
			if (!domain.hasDefinition(key)) {
				return null;
			}
			var clazz:Class = domain.getDefinition(key) as Class;
			return new clazz(0, 0);
		}
		
		public function addAssets(aid:String, data:Object):void {
			if (assets[aid] != null) {
				Logger.warn("asset has already exist");
				return;
			}
			assets[aid] = data;
		}
		
		public function updateUnit(url:String, current:uint, action:uint, direction:uint, unitView:UnitView):void {
			var list:Array = assets[url];
			if (list == null) {
				Logger.warn("asset not found");
				return;
			}
			unitView.view.bitmapData = list[current] as BitmapData;
		}
		
//		public function findAsset(event:Event):Object {
//			var data:Object = event.target.data;
//			addAssets(data);
//		}
	}
}